package config

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/BurntSushi/toml"
)

// Config 配置结构
type Config struct {
	// 基础配置
	Server struct {
		Port int    `toml:"port"`
		Host string `toml:"host"`
	} `toml:"server"`

	// 认证配置
	Auth struct {
		Username string `toml:"username"` // 用户名
		Password string `toml:"password"` // 密码
		Secret   string `toml:"secret"`   // JWT密钥
	} `toml:"auth"`

	// 数据库配置
	Database struct {
		Type     string `toml:"type"`      // 数据库类型：sqlite/mysql
		DSN      string `toml:"dsn"`       // 数据库连接字符串
		LogLevel string `toml:"log_level"` // 日志级别：silent/error/warn/info
	} `toml:"database"`

	// 日志配置
	Log struct {
		Dir     string `toml:"dir"`      // 日志目录
		MaxDays int    `toml:"max_days"` // 日志保留天数
	} `toml:"log"`
}

var (
	// GlobalConfig 全局配置实例
	GlobalConfig Config
)

// LoadConfig 加载配置文件
func LoadConfig() error {
	// 配置文件查找顺序：
	// 1. 当前目录
	// 2. 用户目录下的.crongo
	// 3. /etc/crongo

	configPaths := []string{
		"config.toml",
		filepath.Join(os.Getenv("HOME"), ".crongo", "config.toml"),
		"/etc/crongo/config.toml",
	}

	var configFile string
	for _, path := range configPaths {
		if _, err := os.Stat(path); err == nil {
			configFile = path
			break
		}
	}

	if configFile == "" {
		return fmt.Errorf("未找到配置文件")
	}

	if _, err := toml.DecodeFile(configFile, &GlobalConfig); err != nil {
		return fmt.Errorf("解析配置文件失败: %v", err)
	}

	// 设置默认值
	if GlobalConfig.Server.Port == 0 {
		GlobalConfig.Server.Port = 8080
	}
	if GlobalConfig.Server.Host == "" {
		GlobalConfig.Server.Host = "0.0.0.0"
	}
	if GlobalConfig.Database.Type == "" {
		GlobalConfig.Database.Type = "sqlite"
	}
	if GlobalConfig.Database.DSN == "" {
		GlobalConfig.Database.DSN = "crongo.db"
	}
	if GlobalConfig.Log.Dir == "" {
		GlobalConfig.Log.Dir = "logs"
	}
	if GlobalConfig.Log.MaxDays == 0 {
		GlobalConfig.Log.MaxDays = 30
	}
	if GlobalConfig.Auth.Username == "" {
		GlobalConfig.Auth.Username = "admin"
	}
	if GlobalConfig.Auth.Password == "" {
		GlobalConfig.Auth.Password = "admin888"
	}
	if GlobalConfig.Auth.Secret == "" {
		GlobalConfig.Auth.Secret = "crongo_secret_key"
	}

	return nil
}
